package com.booktrading.controller;

import com.booktrading.model.Book;
import com.booktrading.model.Order;
import com.booktrading.model.User;
import com.booktrading.service.BookService;
import com.booktrading.service.OrderService;
import com.booktrading.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private BookService bookService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> createOrder(@RequestBody Order order) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            
            // 设置买家信息
            order.setBuyerId(currentUser.getId());
            order.setBuyerName(currentUser.getUsername());
            
            // 获取书籍信息
            Book book = bookService.getBookById(order.getBookId());
            
            if (book == null) {
                result.put("success", false);
                result.put("message", "书籍不存在");
                return ResponseEntity.ok(result);
            }
            
            // 检查书籍是否在售
            if (book.getStatus() != 1) {
                result.put("success", false);
                result.put("message", "该书籍已下架，无法购买");
                return ResponseEntity.ok(result);
            }
            
            // 检查是否是购买自己的书籍
            if (book.getSellerId().equals(currentUser.getId())) {
                result.put("success", false);
                result.put("message", "不能购买自己发布的书籍");
                return ResponseEntity.ok(result);
            }
            
            // 设置卖家信息
            order.setSellerId(book.getSellerId());
            order.setSellerName(book.getSellerName());
            
            // 设置订单金额 (默认数量为1)
            order.setBookPrice(book.getPrice());
            order.setBookTitle(book.getTitle());
            
            // 设置订单状态：1-待付款
            order.setStatus(1);
            
            // 设置创建时间
            order.setCreateTime(new Date());
            
            // 创建订单
            Order createdOrder = orderService.createOrder(order);
            
            if (createdOrder != null && createdOrder.getId() != null) {
                result.put("success", true);
                result.put("message", "订单创建成功");
                result.put("orderId", createdOrder.getId());
            } else {
                result.put("success", false);
                result.put("message", "订单创建失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "订单创建失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 我的订单页面
     */
    @GetMapping("/my-orders")
    public String myOrdersPage(Model model) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        if (currentUser == null) {
            return "redirect:/login";
        }
        // 获取用户购买的订单
        List<Order> buyingOrders = orderService.getBuyerOrders(currentUser.getId());
        // 获取用户卖出的订单
        List<Order> sellingOrders = orderService.getSellerOrders(currentUser.getId());
        // 为每个订单补充book信息
        for (Order order : buyingOrders) {
            Book book = bookService.getBookById(order.getBookId());
            order.setBook(book);
        }
        for (Order order : sellingOrders) {
            Book book = bookService.getBookById(order.getBookId());
            order.setBook(book);
        }
        // 状态统计
        Map<Integer, Long> buyingStatusStats = new HashMap<>();
        Map<Integer, Long> sellingStatusStats = new HashMap<>();
        // 统计购买订单状态
        for (Order order : buyingOrders) {
            Integer status = order.getStatus();
            buyingStatusStats.put(status, buyingStatusStats.getOrDefault(status, 0L) + 1);
        }
        // 统计卖出订单状态
        for (Order order : sellingOrders) {
            Integer status = order.getStatus();
            sellingStatusStats.put(status, sellingStatusStats.getOrDefault(status, 0L) + 1);
        }
        model.addAttribute("buyingOrders", buyingOrders);
        model.addAttribute("sellingOrders", sellingOrders);
        model.addAttribute("buyingStatusStats", buyingStatusStats);
        model.addAttribute("sellingStatusStats", sellingStatusStats);
        model.addAttribute("totalBuyingOrders", buyingOrders.size());
        model.addAttribute("totalSellingOrders", sellingOrders.size());
        return "order/my-orders";
    }
    
    /**
     * 订单详情页面
     */
    @GetMapping("/detail/{id}")
    public String orderDetailPage(@PathVariable("id") Long id, Model model) {
        Order order = orderService.getOrderById(id);
        
        if (order == null) {
            return "redirect:/order/my-orders";
        }
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        // 检查权限，只有订单的买家和卖家可以查看订单详情
        if (!order.getBuyerId().equals(currentUser.getId()) && !order.getSellerId().equals(currentUser.getId())) {
            return "redirect:/order/my-orders";
        }
        
        // 获取书籍信息
        Book book = bookService.getBookById(order.getBookId());
        
        model.addAttribute("order", order);
        model.addAttribute("book", book);
        model.addAttribute("currentUser", currentUser);
        
        return "order/detail";
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/cancel/{id}")
    @ResponseBody
    public Map<String, Object> cancelOrder(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        // 获取订单信息
        Order order = orderService.getOrderById(id);
        
        if (order == null) {
            result.put("success", false);
            result.put("message", "订单不存在");
            return result;
        }
        
        // 只有买家可以取消订单
        if (!order.getBuyerId().equals(currentUser.getId())) {
            result.put("success", false);
            result.put("message", "无权取消他人订单");
            return result;
        }
        
        // 只有待付款的订单可以取消
        if (order.getStatus() != 1) {
            result.put("success", false);
            result.put("message", "当前订单状态不允许取消");
            return result;
        }
        
        // 取消订单，更新状态为5（已取消）
        boolean success = orderService.updateOrderStatus(id, 5);
        
        if (success) {
            result.put("success", true);
            result.put("message", "订单取消成功");
        } else {
            result.put("success", false);
            result.put("message", "订单取消失败");
        }
        
        return result;
    }
    
    /**
     * 支付订单
     */
    @PostMapping("/pay/{id}")
    @ResponseBody
    public Map<String, Object> payOrder(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        // 获取订单信息
        Order order = orderService.getOrderById(id);
        
        if (order == null) {
            result.put("success", false);
            result.put("message", "订单不存在");
            return result;
        }
        
        // 只有买家可以支付订单
        if (!order.getBuyerId().equals(currentUser.getId())) {
            result.put("success", false);
            result.put("message", "无权支付他人订单");
            return result;
        }
        
        // 只有待付款的订单可以支付
        if (order.getStatus() != 1) {
            result.put("success", false);
            result.put("message", "当前订单状态不允许支付");
            return result;
        }
        
        // 支付订单，更新状态为2（已支付，待发货）
        boolean success = orderService.updateOrderStatus(id, 2);
        
        if (success) {
            result.put("success", true);
            result.put("message", "支付成功");
        } else {
            result.put("success", false);
            result.put("message", "支付失败");
        }
        
        return result;
    }
    
    /**
     * 发货
     */
    @PostMapping("/ship/{id}")
    @ResponseBody
    public Map<String, Object> shipOrder(@PathVariable("id") Long id, @RequestParam("trackingNumber") String trackingNumber) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        // 获取订单信息
        Order order = orderService.getOrderById(id);
        
        if (order == null) {
            result.put("success", false);
            result.put("message", "订单不存在");
            return result;
        }
        
        // 只有卖家可以发货
        if (!order.getSellerId().equals(currentUser.getId())) {
            result.put("success", false);
            result.put("message", "无权操作他人订单");
            return result;
        }
        
        // 只有已支付待发货的订单可以发货
        if (order.getStatus() != 2) {
            result.put("success", false);
            result.put("message", "当前订单状态不允许发货");
            return result;
        }
        
        // 创建一个更新后的订单对象
        Order updatedOrder = new Order();
        updatedOrder.setId(id);
        updatedOrder.setStatus(3); // 设置为已发货状态
        updatedOrder.setShippingTime(new Date()); // 设置发货时间
        // 设置物流信息可以在Order类中添加跟踪号字段，这里暂时使用备注
        updatedOrder.setRemark("物流单号: " + trackingNumber);
        
        // 更新订单
        boolean success = orderService.updateOrder(updatedOrder);
        
        if (success) {
            result.put("success", true);
            result.put("message", "发货成功");
        } else {
            result.put("success", false);
            result.put("message", "发货失败");
        }
        
        return result;
    }
    
    /**
     * 确认收货
     */
    @PostMapping("/confirm/{id}")
    @ResponseBody
    public Map<String, Object> confirmOrder(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        // 获取订单信息
        Order order = orderService.getOrderById(id);
        
        if (order == null) {
            result.put("success", false);
            result.put("message", "订单不存在");
            return result;
        }
        
        // 只有买家可以确认收货
        if (!order.getBuyerId().equals(currentUser.getId())) {
            result.put("success", false);
            result.put("message", "无权操作他人订单");
            return result;
        }
        
        // 只有已发货待收货的订单可以确认收货
        if (order.getStatus() != 3) {
            result.put("success", false);
            result.put("message", "当前订单状态不允许确认收货");
            return result;
        }
        
        // 创建一个更新后的订单对象
        Order updatedOrder = new Order();
        updatedOrder.setId(id);
        updatedOrder.setStatus(4); // 设置为已完成状态
        updatedOrder.setCompletionTime(new Date()); // 设置完成时间
        
        // 更新订单
        boolean success = orderService.updateOrder(updatedOrder);
        
        if (success) {
            result.put("success", true);
            result.put("message", "确认收货成功");
        } else {
            result.put("success", false);
            result.put("message", "确认收货失败");
        }
        
        return result;
    }
    
    /**
     * 表单方式添加订单（用于页面表单提交）
     */
    @PostMapping("/add")
    public String addOrder(@RequestParam("bookId") Long bookId, Model model) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        if (currentUser == null) {
            return "redirect:/login";
        }

        // 获取书籍信息
        Book book = bookService.getBookById(bookId);
        if (book == null) {
            model.addAttribute("error", "书籍不存在");
            return "redirect:/books/list";
        }
        // 检查是否是购买自己的书籍
        if (book.getSellerId().equals(currentUser.getId())) {
            model.addAttribute("error", "不能购买自己发布的书籍");
            return "redirect:/books/list";
        }
        // 检查书籍是否在售
        if (book.getStatus() != 1) {
            model.addAttribute("error", "该书籍已下架，无法购买");
            return "redirect:/books/list";
        }

        // 构建订单对象
        Order order = new Order();
        order.setBookId(book.getId());
        order.setBookTitle(book.getTitle());
        order.setBookPrice(book.getPrice());
        order.setSellerId(book.getSellerId());
        order.setSellerName(book.getSellerName());
        order.setBuyerId(currentUser.getId());
        order.setBuyerName(currentUser.getUsername());
        order.setStatus(1); // 1-待付款
        order.setCreateTime(new java.util.Date());

        orderService.createOrder(order);
        // 下单成功后跳转到我的订单页面
        return "redirect:/order/my-orders";
    }
} 